<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/14
 * Time: 17:16
 */
class DiaryService
{
    private $autoUidModel;
    private $diaryBodyModel;
    private $diaryListModel;
    private $diaryListCacheModel;

    function __construct()
    {
        $this->autoUidModel             =   new AutoUidModel();
        $this->diaryBodyModel           =   new DiaryBodyModel();
        $this->diaryListModel           =   new DiaryListModel();
        $this->diaryListCacheModel      =   new DiaryListCacheModel();
    }

    /**
     * 更新点滴计数
     * @param $diaryInfo
     * @return bool|int|resource
     */
    public function countTimes($diaryInfo)/*{{{*/
    {
        if (empty($diaryInfo['uid']) || empty($diaryInfo['bodyId']))
        {
            AC::$errorNo    =   'DS001';
            return  FALSE;
        }
        $result =   $this->diaryListModel->countTimes($diaryInfo);

        return  $result;
    }/*}}}*/

    /**
     * 文章进日记
     * @param $articleInfo
     * @param $uid
     * @param $topicId
     * @param $time
     * @return array|bool
     */
    public function articleIntoDiary($articleInfo, $uid, $topicId, $time = ''){
        // 获取用户详情
        $userInfo = $this->autoUidModel->getUserInfo($uid);
        if (empty($userInfo) || empty($articleInfo)){
            return false;
        }

        // 数据组装
        $diaryData = array(
            'uid'    =>    $uid,
            'nickname' =>  $userInfo['nickname'],
            'title'  =>    $articleInfo['title'],
            'content'=>    empty($articleInfo['summary']) ? '分享文章' : $articleInfo['summary'],
            'theme'  =>    0
        );

        if(!empty($time) && strtotime($time) > AC::SERVER_TIME) {
            $diaryData['secret'] = 1;
        }

        $summary = UK::cleanStrStrict($articleInfo['summary']);
        $title   = UK::cleanStrStrict($articleInfo['title']);
        if(empty($summary)) {
            $content = UK::checkHTMLContent($articleInfo['content']);
            $summary = UK::getstr($content, AC::ARTICLESUMMARYLENGTH,'',2);
        }

        $tmp = array(
            'url_type'          =>  'article',
            'url_type_id'       =>  $articleInfo['aid'],
            'url_type_uid'      =>  $uid,
            'url_title'         =>  $title,
            'url_content'       =>  $summary,
            'url_image'         =>  $articleInfo['cover'],
            'url_action'        =>  AC::$openUrl['article_info'].'aid='.$articleInfo['aid'].'&author_uid='.$uid,
            'url_extend'        =>  array(
                'cover'         =>  $articleInfo['cover'],
                'uid'           =>  $uid,
                'nickname'      =>  $articleInfo['user']['nickname'],
                'avatar'        =>  $articleInfo['user']['avatar']
            ),
        );
        //为保证文章能正确解析，此处多进行一次base64_encode!,使用时注意解析！
        $diaryData['extras']['article'][]	=	base64_encode(json_encode($tmp,JSON_UNESCAPED_UNICODE));;
        $diaryData['extras']            =   json_encode($diaryData['extras'],JSON_UNESCAPED_UNICODE);
        // 入库
        $diaryId    =   $this->diaryBodyModel->addDiaryBody($diaryData);

        if (empty($diaryId)){
            UK::varDump(AC::$errorNo, __METHOD__);
            return  false;
        }

        $diaryData['bodyId']=   $this->diaryBodyModel->getBodyId($diaryData['uid'], $diaryId);
        if (empty($diaryData['bodyId']))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  false;
        }
        $diaryData['topics'] = $this->assembleDiaryTopics($topicId);
        if (AC::$errorNo) return false;
        $diaryListInsert=   $this->diaryListModel->addDiaryList($diaryData);
        if (empty($diaryListInsert))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  false;
        }

//        $result =   array('bodyId' => $diaryData['bodyId']);
        //将日志加入redis缓存
        $this->diaryListModel->getDiaryInfoByBodyId($diaryData['bodyId']);
        if (!empty($diaryData['secret'])){
            AC::$userStatistics[$diaryData['uid']]['secretDiaryTimes']  =   1;
            return  $diaryData;
        }
        $this->diaryListCacheModel->addUserTimeline($diaryData['uid'], $diaryData['bodyId']);
        #  feed & statistics    /*{{{*/
        AC::$userStatistics[$diaryData['uid']]['diaryTimes']    =   1;
        AC::$feedInfo   =   array(
            'uid'               =>  $diaryData['uid'],
            'eUid'              =>  $diaryData['uid'],
            'eNickname'         =>  $diaryData['nickname'],
            'authorUid'         =>  $diaryData['uid'],
            'authorNickname'    =>  $diaryData['nickname'],
            'bodyId'            =>  $diaryData['bodyId'],
            'type'              =>  AC::FEED_DIARY,
            'label'             =>   (isset($diaryData['label']) && intval($diaryData['label']) > 0 && intval($diaryData['label']) <= AC::DIARY_TAG_MAXID) ? intval($diaryData['label']) : 0
        );

        strlen($diaryData['content']) > 0    &&  AC::$feedInfo['content']    =   $diaryData['content'];
        strlen($diaryData['title']) > 0      &&  AC::$feedInfo['content']    =   $diaryData['title'];
        strlen(AC::$feedInfo['content']) < 1 &&  AC::$feedInfo['content']    =   ' write Diary, No title ? No content ? ! ';

        $this->sendDiaryToTopic($topicId, $diaryData['topics'], $diaryData);

        return $diaryData;
    }

    /**
     * 组装日记topics
     * @param  $topic_id
     * @return boolean|string
     */
    public function assembleDiaryTopics ($topic_id) {
        $topics = '';
        if($topic_id) {
            $groupInfoModel = new GroupInfoModel();
            $diaryTopic = $groupInfoModel->getDiaryTopicInfo($topic_id);
            $this->checkDiaryTopicIsValid($diaryTopic);
            if (AC::$errorNo) {
                UK::varDump(AC::$errorNo, __METHOD__);
                return FALSE;
            }

            $topics = UK::var_json_encode(array('gid' => $topic_id, 'name' => $diaryTopic['name'], 'type' => $diaryTopic['type']));
        }

        return $topics;
    }

    /**
     * 验证点滴话题有效性
     * @param  $topic
     * @return boolean
     */
    private function checkDiaryTopicIsValid ($topic)
    {
        if (empty($topic)) {
            AC::$errorNo = 'DS002';
            return false;
        } else {
            if ($topic['status'] == AC::$diaryTopicCf['delete_status']) {
                AC::$errorNo = 'DS003';
                return false;
            }
        }
        return true;
    }
    /**
     * 话题下热门点滴
     * @param $bodyId
     * @param $time
     * @return bool
     */
    public function addHotDiary($bodyId, $time = AC::SERVER_TIME) {
        if(empty($bodyId)) {
            return false;
        }
        try {
            $diaryInfo = $this->diaryListModel->getDiaryInfoByBodyId($bodyId);
            if (empty($diaryInfo) || empty($diaryInfo['topics'])) {
                return false;
            }
            $topic = $this->diaryListModel->getDiaryTopic($diaryInfo['topics']);

            $topicHotDiary = new RecommendModel();
            $result = $topicHotDiary->saveHotDiary($topic[0]['id'], $bodyId);
            if (empty($result)) {
                return false;
            }
            //更新缓存
            $result = $this->diaryListCacheModel->setTopicHotDiary($topic[0]['id'], $bodyId, $time);
            if (empty($result)) {
                return false;
            }
        } catch (\Exception $e) {
            UK::saveLog(__FUNCTION__.'.log', '更新热门点滴失败：[$e]'. print_r($e, true). "\r\n", TRUE);
        }

        return true;
    }

    public function removeTopicHotDiaryCache() {
        try {
            //更新数据库
            $topicHotDiary = new RecommendModel();
            $topicHotDiary->removeTopicHotDiaryList();
            //清除缓存
            $topicList = $this->diaryListCacheModel->getTopicHotDiaryKeys(0, -1);
            if(empty($topicList)) return true;
            foreach ($topicList as $topic_id) {
                $this->diaryListCacheModel->delTopicHotDiaryKey($topic_id);
            }
        } catch (\Exception $e) {
            UK::saveLog(__FUNCTION__.'.log', '更新热门点滴失败：[$e]'. print_r($e, true). "\r\n", TRUE);
        }
        return true;
    }

    /**
     * 将点滴添加进话题点滴列表
     * @param  $topic_id
     * @param  $topics
     * @param  $diaryInfo
     * @return boolean
     */
    public function sendDiaryToTopic ($topic_id, $topics, $diaryInfo) {
        if (empty($topic_id) || empty($topics) || AC::$errorNo) {
            return false;
        }

        $tmp = array(
            'gid'     => $topic_id,
            'uid'     => $diaryInfo['uid'],
            'bodyId'  => $diaryInfo['bodyId'],
            'title'   => $diaryInfo['title'],
            'content' => $diaryInfo['content']
        );
        $topicModel = new TopicModel();
        $topicModel->addDiaryToTopic($tmp);
        AC::$errorNo = '';
        return true;
    }

    public function updateDiaryTopic ($diaryBodyId, $authorUid, $topicId) {
        //获取话题详情
        $topics = $this->assembleDiaryTopics($topicId);

        if (AC::$errorNo) return false;
        //获取点滴详情
        $diaryInfo = $this->diaryListModel->getDiaryInfoByBodyId($diaryBodyId);

        if(empty($diaryInfo)) return false;
        //更新点滴列表
        $diaryData = [
            'uid'       =>  $authorUid,
            'bodyId'    =>  $diaryBodyId,
            'topics'    =>  $topics,
        ];
        $this->diaryListModel->updateDiaryList($diaryData);

        //重建缓存
        $this->diaryListCacheModel->delDiaryCache($diaryInfo['bodyId']);

        //将日志加入redis缓存
        $this->diaryListModel->getDiaryInfoByBodyId($diaryInfo['bodyId']);

        //更新点滴话题
        $topicModel = new TopicModel();
        $topicModel->updateTopicDiary($diaryBodyId, $topicId);
    }

}